const express = require("express");
const router = express.Router();
const { VisitLog } = require("../../models");
const { NotFound } = require("http-errors");
const { success, failure } = require("../../utils/responses");
const { Op } = require("sequelize");

// 建议在数据库中创建以下索引以提高查询性能:
// CREATE INDEX idx_visitlog_route ON VisitLogs(route);
// CREATE INDEX idx_visitlog_method ON VisitLogs(method);
// CREATE INDEX idx_visitlog_originname ON VisitLogs(originName);
// CREATE INDEX idx_visitlog_user ON VisitLogs(user);
// CREATE INDEX idx_visitlog_level ON VisitLogs(level);
// CREATE INDEX idx_visitlog_timestamp ON VisitLogs(timestamp);
// CREATE INDEX idx_visitlog_composite ON VisitLogs(level, timestamp);

/**
 * 查询日志列表
 * GET /admin/logs
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    // 限制最大页面大小，防止查询过多数据
    const maxPageSize = Math.min(pageSize, 100);

    const condition = {
      where: {},
      order: [["id", "DESC"]],
      limit: maxPageSize,
      offset: offset,
    };

    // 优化：精确匹配比模糊匹配性能更好
    if (query.route) {
      // 如果前端明确要求模糊匹配，使用like
      if (query.routeExact === "false") {
        condition.where.route = {
          [Op.like]: `%${query.route}%`,
        };
      } else {
        // 默认使用精确匹配以提高性能
        condition.where.route = query.route;
      }
    }

    if (query.method) {
      condition.where.method = query.method;
    }

    if (query.originName) {
      condition.where.originName = query.originName;
    }

    if (query.user) {
      condition.where.user = query.user;
    }

    if (query.level) {
      condition.where.level = query.level;
    }

    // 优化：日期范围查询
    if (query.startDate && query.endDate) {
      condition.where.timestamp = {
        [Op.between]: [query.startDate, query.endDate],
      };
    } else if (query.startDate) {
      // 只有开始时间
      condition.where.timestamp = {
        [Op.gte]: query.startDate,
      };
    } else if (query.endDate) {
      // 只有结束时间
      condition.where.timestamp = {
        [Op.lte]: query.endDate,
      };
    }

    // 优化：使用findAndCountAll的性能选项
    const { count, rows } = await VisitLog.findAndCountAll({
      ...condition,
      distinct: true, // 确保计数准确
    });

    success(req, res, "查询日志列表成功。", {
      list: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize: maxPageSize,
      },
    });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 快速查询日志接口 - 专门用于高频查询场景
 * GET /admin/logs/fast-search
 */
router.get("/fast-search", async function (req, res) {
  try {
    const query = req.query;

    // 只支持高频查询字段，避免复杂查询
    const whereConditions = {};

    // 优化：只允许精确匹配查询，提高性能
    if (query.level) {
      whereConditions.level = query.level;
    }

    if (query.method) {
      whereConditions.method = query.method;
    }

    if (query.user) {
      whereConditions.user = query.user;
    }

    // 时间范围查询
    if (query.startDate && query.endDate) {
      whereConditions.timestamp = {
        [Op.between]: [query.startDate, query.endDate],
      };
    }

    // 如果没有查询条件，返回错误
    if (Object.keys(whereConditions).length === 0) {
      return failure(req, res, new Error("至少需要提供一个查询条件"));
    }

    // 优化：只查询必要的字段
    const attributes = query.fields
      ? query.fields.split(",")
      : ["id", "ip", "route", "method", "level", "user", "timestamp"];

    // 优化：设置合理的查询限制
    const limit = Math.min(Math.abs(Number(query.limit)) || 10, 100);

    const logs = await VisitLog.findAll({
      where: whereConditions,
      attributes: attributes,
      order: [["id", "DESC"]],
      limit: limit,
    });

    success(req, res, "快速查询日志成功。", {
      list: logs,
      count: logs.length,
    });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 统计日志接口 - 获取日志统计信息
 * GET /admin/logs/stats
 */
router.get("/stats", async function (req, res) {
  try {
    const query = req.query;

    // 构建基础查询条件
    let whereConditions = {};
    if (query.startDate && query.endDate) {
      whereConditions.timestamp = {
        [Op.between]: [query.startDate, query.endDate],
      };
    }

    // 优化：使用聚合查询获取统计数据，避免加载大量数据
    const [levelStats, methodStats, userStats, recentCount] = await Promise.all(
      [
        // 按日志级别统计
        VisitLog.findAll({
          where: whereConditions,
          attributes: [
            "level",
            [sequelize.fn("COUNT", sequelize.col("level")), "count"],
          ],
          group: ["level"],
          raw: true,
        }),

        // 按请求方法统计
        VisitLog.findAll({
          where: whereConditions,
          attributes: [
            "method",
            [sequelize.fn("COUNT", sequelize.col("method")), "count"],
          ],
          group: ["method"],
          raw: true,
        }),

        // 按用户统计（前10名）
        VisitLog.findAll({
          where: whereConditions,
          attributes: [
            "user",
            [sequelize.fn("COUNT", sequelize.col("user")), "count"],
          ],
          group: ["user"],
          order: [[sequelize.fn("COUNT", sequelize.col("user")), "DESC"]],
          limit: 10,
          raw: true,
        }),

        // 最近7天日志数量
        VisitLog.count({
          where: {
            ...whereConditions,
            timestamp: {
              [Op.gte]: new Date(new Date() - 7 * 24 * 60 * 60 * 1000),
            },
          },
        }),
      ]
    );

    success(req, res, "日志统计查询成功。", {
      levelStats,
      methodStats,
      userStats,
      recentCount,
    });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 查询日志详情
 * GET /admin/logs/:id
 */
router.get("/:id", async function (req, res) {
  try {
    // 优化：直接通过主键查询，性能最佳
    const { id } = req.params;

    // 验证ID是否为有效数字
    if (!id || isNaN(Number(id))) {
      throw new NotFound(`无效的日志ID: ${id}。`);
    }

    const log = await VisitLog.findByPk(id);
    if (!log) {
      throw new NotFound(`ID: ${id}的日志未找到。`);
    }

    success(req, res, "查询日志成功详情。", { log });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 清空全部日志
 * DELETE /admin/logs/clear
 */
router.delete("/clear", async function (req, res) {
  try {
    await VisitLog.destroy({ truncate: true, restartIdentity: true });

    success(req, res, "清空日志成功。");
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 删除日志
 * DELETE /admin/logs/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    // 优化：直接通过主键查询，性能最佳
    const { id } = req.params;

    // 验证ID是否为有效数字
    if (!id || isNaN(Number(id))) {
      throw new NotFound(`无效的日志ID: ${id}。`);
    }

    const visitLog = await VisitLog.findByPk(id);
    if (!visitLog) {
      throw new NotFound(`ID: ${id}的日志未找到。`);
    }

    await visitLog.destroy();

    success(req, res, "删除日志成功。");
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 批量删除日志
 * POST /admin/logs/batch-delete
 */
router.post("/batch-delete", async function (req, res) {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      throw new NotFound("请提供要删除的日志ID列表。");
    }

    // 验证所有ID是否为有效数字
    const validIds = ids.filter((id) => id && !isNaN(Number(id)));
    if (validIds.length === 0) {
      throw new NotFound("没有提供有效的日志ID。");
    }

    // 批量删除
    const deletedCount = await VisitLog.destroy({
      where: {
        id: {
          [Op.in]: validIds,
        },
      },
    });

    success(req, res, `成功删除${deletedCount}条日志。`, {
      deletedCount,
    });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 按条件删除日志
 * POST /admin/logs/delete-by-condition
 */
router.post("/delete-by-condition", async function (req, res) {
  try {
    const { condition } = req.body;

    if (!condition) {
      throw new NotFound("请提供删除条件。");
    }

    // 构建删除条件
    const whereConditions = {};

    if (condition.level) {
      whereConditions.level = condition.level;
    }

    if (condition.method) {
      whereConditions.method = condition.method;
    }

    if (condition.user) {
      whereConditions.user = condition.user;
    }

    if (condition.startDate && condition.endDate) {
      whereConditions.timestamp = {
        [Op.between]: [condition.startDate, condition.endDate],
      };
    }

    // 执行删除
    const deletedCount = await VisitLog.destroy({
      where: whereConditions,
    });

    success(req, res, `成功删除${deletedCount}条日志。`, {
      deletedCount,
    });
  } catch (error) {
    failure(req, res, error);
  }
});

module.exports = router;
